from flask import Blueprint, render_template, g, request, redirect, url_for, flash
from blueprint.decorators import login_required
from exts import db
from forms import QuestionForm, AnswerForm
from models import QuestionModel, AnswerModel
from sqlalchemy import or_

bp = Blueprint('qa', __name__, '/')


@bp.app_template_filter('cdecode')
def content_decode(content):
    content = content.decode('utf-8')
    return content


@bp.route('/')
def index():
    # questions = QuestionModel.query.order_by(QuestionModel.create_time.desc()).all()
    questions = QuestionModel.query.order_by(db.text('-create_time')).all()
    pythonquestion = QuestionModel.query.filter(QuestionModel.category == 'python').all()
    initporjctquestion = QuestionModel.query.filter(QuestionModel.category == '嵌入式').all()
    clangquestion = QuestionModel.query.filter(QuestionModel.category == 'c语言').all()
    otherquestion = QuestionModel.query.filter(QuestionModel.category == '其他').all()
    return render_template('index.html', questions=questions, pythonquestion=pythonquestion,
                           initporjctquestion=initporjctquestion, clangquestion=clangquestion,
                           otherquestion=otherquestion)


@bp.route('/question/public/', methods=["GET", "POST"])
@login_required
def public_question():
    # 判断是否已经登录
    if request.method == "GET":
        return render_template('public_question.html')
    else:
        form = QuestionForm(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data.encode('utf-8')
            category = form.category.data
            question = QuestionModel(title=title, content=content, author=g.user, category=category)
            db.session.add(question)
            db.session.commit()
            return redirect('/')
        else:
            flash('标题或者内容错误')
            return redirect(url_for('qa.public_question'))


@bp.route('/question/<int:question_id>/')
def question_detail(question_id):
    question = QuestionModel.query.get(question_id)
    return render_template('detail.html', question=question)


@bp.route('/answer/<int:question_id>', methods=['POST'])
@login_required
def answer(question_id):
    form = AnswerForm(request.form)
    if form.validate():
        content = form.content.data.encode('utf-8')
        answer_model = AnswerModel(content=content, author=g.user, question_id=question_id)
        db.session.add(answer_model)
        db.session.commit()
        return redirect(url_for('qa.question_detail', question_id=question_id))
    else:
        flash("表单验证失败")
        return redirect(url_for("qa.question_detail", question_id=question_id))


@bp.route('/search/')
def search():
    q = request.args.get('q')
    questions = QuestionModel.query.filter(or_(QuestionModel.title.contains(q), QuestionModel.content.contains(q)))
    return render_template('index.html', questions=questions)
